package com.drools.rule;

import com.alibaba.fastjson.JSON;
import com.drools.rule.req.ActionReq;
import com.drools.rule.req.LoginActionReq;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;

import java.util.ArrayList;

/**
 * drools 动态生成规则
 * */
public class RuleTest {

    public static void main(String[] args) {

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("package com.drools.rule.req").append("\n");
        stringBuilder.append("import com.drools.rule.req.LoginActionReq").append("\n");
        stringBuilder.append("rule login_rule_1 ").append("\n");
        stringBuilder.append("when\n" + " $s:LoginActionReq(loginNum==1) ").append("\n");
        stringBuilder.append("then\n" + " $s.amount=10; ").append("\n");
        stringBuilder.append("update($s); ").append("\n");
        stringBuilder.append("end ").append("\n");

        stringBuilder.append("rule login_rule_2 ").append("\n");
        stringBuilder.append("when\n" + " $s:LoginActionReq(amount==10) ").append("\n");
        stringBuilder.append("then\n" + " $s.flag=true; ").append("\n");
        stringBuilder.append("System.out.println($s.flag); ").append("\n");
        stringBuilder.append("update($s); ").append("\n");
        stringBuilder.append("end ").append("\n");

        System.out.println(stringBuilder.toString());
        KieHelper helper = new KieHelper();

        helper.addContent(stringBuilder.toString(), ResourceType.DRL);


        KieSession kSession = helper.build().newKieSession();
        LoginActionReq actionReq = new LoginActionReq();
        actionReq.setLoginActionType("LOGIN");
        actionReq.setLoginNum(1);
        System.out.println("req : "+ JSON.toJSONString(actionReq));

        kSession.insert(actionReq);
        kSession.fireAllRules();
        kSession.dispose();
        System.out.println("resp : "+ JSON.toJSONString(actionReq));


    }
}
